﻿using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
using Sustainalytics.Utils.Configuration;


namespace Sustainalytics.PregenerateScreeningReports.Service
{
    partial class PregenerateScreeningReports : ServiceBase
    {

        Orchestrator serviceBL;
        OldFilesCleaner cleaner; 
             
        public PregenerateScreeningReports()
        {
            InitializeComponent();
        }

        public void Start(string[] args)
        {
            OnStart(args);
        }

        public void Stop()
        {
            Stop();
        }

        protected override void OnStart(string[] args)
        {
            //TODO add logging 
            foreach (var s in args)
                Console.WriteLine(s);

            PSREventSource.Log.Start( System.Environment.UserInteractive, Process.GetCurrentProcess().Id, string.Join(" ", args));

            if (args.Length == 0)
            {
                try
                {
                    cleaner = new OldFilesCleaner(SettingsHelper.Read<string>("TempPath", System.IO.Path.GetTempPath()));
                    serviceBL = Orchestrator.NewInstanceFromConfig();
                    Task.Run(() => serviceBL.Run()).ContinueWith(t =>
                    {
                        PSREventSource.Log.Exit(Process.GetCurrentProcess().Id);
                        TTLManager.Shutdown();
                    });
                }
                catch (Exception ex)
                {
                    PSREventSource.Log.Exception(ex);
                    TTLManager.Shutdown();
                }
            }

            if (args.Length == 2)
            {
                // run as subprocess - work synchronously         
                var processor = OneReportWorkerProcess.NewInstanceFromConfig(args);
                processor.Run();

                PSREventSource.Log.Exit(Process.GetCurrentProcess().Id);
                Environment.Exit(0);
            }
        }

        protected override void OnStop()
        {
            cleaner.Wait();
            PSREventSource.Log.Stop(Process.GetCurrentProcess().Id);
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }



    }
}
